/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bwhx.etapedemo;


import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bwhx.util.ETapeDecrypt;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;

public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
    private static final int REQUEST_SELECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int UART_PROFILE_READY = 10;
    public static final String TAG = "nRFUART";
    private static final int UART_PROFILE_CONNECTED = 20;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private static final int STATE_OFF = 10;

    private int reset_all = 0;
    private int reset_correct = 0;
    private int reset_Unnormal = 0;
    private int reset_fasle = 0;

    private int mState = UART_PROFILE_DISCONNECTED;
    private com.bwhx.etapedemo.UartService mService = null;
    private BluetoothDevice mDevice = null;
    private BluetoothAdapter mBtAdapter = null;
    private ListView messageListView;
    private ArrayAdapter<String> listAdapter;
    private Button btnConnectDisconnect, btnSend, sendButtonOnTimer;
    private Button resetButtontongji;
    private boolean isOnTimer = false;
    private EditText edtMessage;

    private long ontimer = 500L;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        messageListView = (ListView) findViewById(R.id.listMessage);
        listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
        messageListView.setAdapter(listAdapter);
        messageListView.setDivider(null);
        btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
        btnSend = (Button) findViewById(R.id.sendButton);
        edtMessage = (EditText) findViewById(R.id.sendText);
        sendButtonOnTimer = (Button) findViewById(R.id.sendButtonOnTimer);
        resetButtontongji = (Button) findViewById(R.id.resetButtontongji);
        service_init();


        // Handler Disconnect & Connect button
        btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBtAdapter.isEnabled()) {
                    Log.i(TAG, "onClick - BT not enabled yet");
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                } else {
                    if (btnConnectDisconnect.getText().equals("连接")) {

                        //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                        Intent newIntent = new Intent(MainActivity.this, com.bwhx.etapedemo.DeviceListActivity.class);
                        startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                    } else {
                        //Disconnect button pressed
                        if (mDevice != null) {
                            mService.disconnect();

                        }
                    }
                }
            }
        });
        // Handler Send button  
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText = (EditText) findViewById(R.id.sendText);
                String message = "OB";//editText.getText().toString();
                byte[] value;
                try {
                    //send data to service
                    value = message.getBytes("UTF-8");
                    mService.writeRXCharacteristic(value);
                    //Update the log with time stamp
                    //String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                    //listAdapter.add("["+currentDateTimeString+"] TX: "+ message);
                    //messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                    //edtMessage.setText("");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        });

        sendButtonOnTimer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOnTimer) {
                    View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.ontimer, null);
                    final EditText et_timer = (EditText) view.findViewById(R.id.et_timer);
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("间隔时间设置")
                            .setView(view)
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String str = et_timer.getText().toString();
                                    if (TextUtils.isEmpty(str)) {
                                        Toast.makeText(MainActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
                                    } else {
                                        ontimer = Long.parseLong(str);
                                        mHandler.sendEmptyMessageDelayed(0, ontimer);
                                        sendButtonOnTimer.setText("取消获取");
                                        isOnTimer = true;
                                    }

                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .create().show();
                } else {
                    sendButtonOnTimer.setText("定时获取");
                    isOnTimer = false;
                    mHandler.removeMessages(0);
                }

            }
        });
        resetButtontongji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset_all = 0;
                reset_correct = 0;
                reset_Unnormal = 0;
                reset_fasle = 0;
            }
        });
        // Set initial UI state

    }

    //UART service connected/disconnected
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((com.bwhx.etapedemo.UartService.LocalBinder) rawBinder).getService();
            Log.d(TAG, "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                //finish();
            }

        }

        public void onServiceDisconnected(ComponentName classname) {
            ////     mService.disconnect(mDevice);
            mService = null;
        }
    };

    private Handler mHandler = new Handler() {
        @Override

        //Handler events that received from UART service 
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String message = "OB";//editText.getText().toString();
                    byte[] value;
                    try {
                        //send data to service
                        value = message.getBytes("UTF-8");
                        mService.writeRXCharacteristic(value);
                        //Update the log with time stamp
                        //String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                        //listAdapter.add("["+currentDateTimeString+"] TX: "+ message);
                        //messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                        //edtMessage.setText("");
                    } catch (UnsupportedEncodingException e) {

                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessageDelayed(0, ontimer);
                    break;
            }
        }
    };

    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            final Intent mIntent = intent;
            //*********************//
            if (action.equals(UartService.ACTION_GATT_CONNECTEDECHI)) {
                Log.e("1", "ACTION_GATT_CONNECTED");
                runOnUiThread(new Runnable() {
                    public void run() {
                        String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                        Log.d(TAG, "UART_CONNECT_MSG");
                        btnConnectDisconnect.setText("取消连接");
                        edtMessage.setEnabled(true);
                        btnSend.setEnabled(true);
                        sendButtonOnTimer.setEnabled(true);
                        ((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - 准备");
                        listAdapter.add("[" + currentDateTimeString + "] 已连接到: " + mDevice.getName());
                        messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                        mState = UART_PROFILE_CONNECTED;
                    }
                });
            }

            //*********************//
            if (action.equals(UartService.ACTION_GATT_DISCONNECTEDECHI)) {
                Log.e("2", "ACTION_GATT_DISCONNECTED");
                runOnUiThread(new Runnable() {
                    public void run() {
                        String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                        Log.d(TAG, "UART_DISCONNECT_MSG");
                        btnConnectDisconnect.setText("连接");
                        edtMessage.setEnabled(false);
                        btnSend.setEnabled(false);
                        sendButtonOnTimer.setEnabled(false);
                        ((TextView) findViewById(R.id.deviceName)).setText("未连接");
                        listAdapter.add("[" + currentDateTimeString + "] 断开连接: " + mDevice.getName());
                        mState = UART_PROFILE_DISCONNECTED;
                        mService.close();
                        //setUiState();

                    }
                });
            }


            //*********************//
            if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVEREDECHI)) {
                Log.e("3", "ACTION_GATT_SERVICES_DISCOVERED");
                mService.enableTXNotification();
            }
            //*********************//
            if (action.equals(UartService.ACTION_DATA_AVAILABLEECHI)) {
                Log.e("4", "ACTION_DATA_AVAILABLE");
                String txValue = intent.getStringExtra(com.bwhx.etapedemo.UartService.EXTRA_DATA);
                JSONObject obj = null;
                try {
                    obj = new JSONObject(txValue);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                final JSONObject finalObj = obj;

                runOnUiThread(new Runnable() {
                    public void run() {
                        //判断是电量
                        if(finalObj.has("powerData")){
                            try {
                                int powerData = finalObj.getInt("powerData");
                                String strValuePower = String.format("%d", powerData);
                                //String strValue16	 = String.format("(%#x%#x%#x%#x%#x%#x)",
                                //		txValue[0], txValue[1], txValue[2], txValue[3], txValue[4], txValue[5]);
                                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                                listAdapter.add("[" + currentDateTimeString + "]当前电量(已归零）: " + strValuePower + "%");
                                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else if(finalObj.has("data")) {
                            try {
                                Long data = finalObj.getLong("data");
                                // 解析数据
                                long nValueMM = data;
                                String strValueMM = String.format("%d", nValueMM);
                                double fValueYingCun = nValueMM * 0.0393701;
                                String strValueYingCun = String.format("%.2f", fValueYingCun);

                                //String strValue16	   = String.format("(%#x%#x%#x%#x%#x%#x)",
                                //		txValue[0], txValue[1], txValue[2], txValue[3], txValue[4], txValue[5]);

                                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                                listAdapter.add("[" + currentDateTimeString + "]长度: " + strValueMM + "毫米,   " + strValueYingCun + "英寸");
                                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                });
            }
            //*********************//
            if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UARTECHI)) {
                showMessage("设备不支持UART,未连接!");
                mService.disconnect();
            }
        }
    };

    private void service_init() {
        Intent bindIntent = new Intent(this, com.bwhx.etapedemo.UartService.class);
        bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTEDECHI);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTEDECHI);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVEREDECHI);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLEECHI);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UARTECHI);
        return intentFilter;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()");

        try {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
        } catch (Exception ignore) {
            Log.e(TAG, ignore.toString());
        }
        unbindService(mServiceConnection);
        mService.stopSelf();
        mService = null;

    }

    @Override
    protected void onStop() {
        Log.d(TAG, "onStop");
        super.onStop();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause");
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        if (!mBtAdapter.isEnabled()) {
            Log.i(TAG, "onResume - BT not enabled yet");
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case REQUEST_SELECT_DEVICE:
                //When the DeviceListActivity return, with the selected device address
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
                    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
                    ETapeDecrypt.device = mDevice;
                    Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + "mserviceValue" + mService);
                    ((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - 连接中");
                    mService.connect(deviceAddress);


                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "蓝牙已经打开", Toast.LENGTH_SHORT).show();

                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, "打开蓝牙有问题  ", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                Log.e(TAG, "错误的请求码");
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

    }


    private void showMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }


    @Override
    public void onBackPressed() {
        if (mState == UART_PROFILE_CONNECTED) {
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
            showMessage("    程序转到后台运行,\n若想退出请先断开连接.");
        } else {
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle(R.string.popup_title)
                    .setMessage(R.string.popup_message)
                    .setPositiveButton(R.string.popup_yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton(R.string.popup_no, null)
                    .show();
        }
    }
}
